//
//  HomeCell.m
//  MyLittleBrother
//
//  Created by speeda on 17/7/24.
//  Copyright © 2017年 speeda. All rights reserved.
//

#import "HomeCell.h"
#import "ArticleModel.h"
#import <SDWebImage/UIButton+WebCache.h>
#import "CommentModel.h"
#import "LLPhotoBrowser.h"
#import "LLPhotoCell.h"
#import "Utility.h"

@interface HomeCell () <UICollectionViewDataSource,UICollectionViewDelegate,LLPhotoBrowserDelegate,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIButton *headButton;
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

//collectionView
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *collectionViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *collectionViewTrailing;
//话题
@property (weak, nonatomic) IBOutlet UILabel *talkLabel;
//盒子数
@property (weak, nonatomic) IBOutlet UIButton *boxNumButton;
//评论数
@property (weak, nonatomic) IBOutlet UIButton *commentNumButton;
//图片数组
@property (nonatomic, strong) NSArray *imgsArray;

@property (weak, nonatomic) IBOutlet UILabel *commentLabelOne;
@property (weak, nonatomic) IBOutlet UILabel *commentLabelTwo;
@property (weak, nonatomic) IBOutlet UILabel *commentLabelThree;

////评论数组
@property (nonatomic, strong) NSArray *commentArray;

@end

@implementation HomeCell

static NSString * const reuseIdentifier = @"homeCell";

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
}


- (void)setArticleItem:(ArticleModel *)articleItem {
    
    [self.headButton sd_setBackgroundImageWithURL:[NSURL URLWithString:articleItem.b_headimg] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"img_touxiang"]];
    self.userNameLabel.text = articleItem.b_nickname;
    self.timeLabel.text = [NSString timeWithTimeIntervalString:articleItem.b_ctime];
    if (articleItem.b_article.length) {
    
        NSMutableAttributedString *attrStr = [Utility emotionStrWithString:[NSString stringWithFormat:@"%@\n",articleItem.b_article] plistName:@"emoticons.plist" y:-5];
        self.titleLabel.attributedText = attrStr;

    }else {
    
        self.titleLabel.text = articleItem.b_article;
    }

    [self.boxNumButton setTitle:articleItem.b_box_sum forState:UIControlStateNormal];
    if (articleItem.b_topic_txt != NULL) {
        self.talkLabel.text = [NSString stringWithFormat:@"#%@#",articleItem.b_topic_txt];
    }else {
    
        self.talkLabel.text = nil;
    }
    NSString *commentNumber = articleItem.b_comments_sum;
    [self.commentNumButton setTitle:commentNumber forState:UIControlStateNormal];
    
    
    if (articleItem.b_imgs.length) {
        
        self.imgsArray = [articleItem.b_imgs componentsSeparatedByString:@"|"];
        
            [self initCollectionView];
        
    } else {
        
        self.collectionViewHeight.constant = 0;
    }
    
    self.commentArray = [CommentModel mj_objectArrayWithKeyValuesArray:articleItem.comment];

    for (int i = 0; i < self.commentArray.count; i++) {
        
        switch (i) {
            case 0:
                self.commentLabelOne.attributedText = [self setAttributes:i];
                break;
            case 1:
                self.commentLabelTwo.attributedText = [self setAttributes:i];
                break;
            case 2:
                self.commentLabelThree.attributedText = [self setAttributes:i];
                break;
                
            default:
                break;
        }
    }
}



- (NSMutableAttributedString *)setAttributes:(int)i {

    CommentModel *commentItem = self.commentArray[i];
    NSDictionary *dict = @{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName:[UIFont fontWithName:@"Helvetica-Bold" size:14]};
    
    NSDictionary *dic = @{NSForegroundColorAttributeName:[UIColor lightGrayColor], NSFontAttributeName:[UIFont systemFontOfSize:14]};
    
    NSMutableAttributedString *str = nil;
    NSMutableAttributedString *comment = [Utility emotionStrWithString:commentItem.b_comment plistName:@"emoticons.plist" y:-5];
    [comment addAttributes:dic range:NSMakeRange(0, comment.length)];
    
    if (commentItem.b_re_nickname != NULL) {
        str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ 回复 %@：",commentItem.b_nickname,commentItem.b_re_nickname]];
        [str addAttributes:dict range:NSMakeRange(commentItem.b_nickname.length + 4, commentItem.b_re_nickname.length)];
        [str appendAttributedString:comment];
    } else {
        
        str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@：",commentItem.b_nickname]];
        [str appendAttributedString:comment];
    }
    [str addAttributes:dict range:NSMakeRange(0, commentItem.b_nickname.length)];
    
    return str;
}



static NSInteger spacing = 10;

- (void)initCollectionView {

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat width = SCREEN_WIDTH - 40 - 2 * spacing;
    if (self.imgsArray.count <= 3) {
        
        self.collectionViewHeight.constant = width / 3;
        layout.itemSize = CGSizeMake(width / 3, width / 2);
        
    }else if(self.imgsArray.count == 4) {
        
        self.collectionViewTrailing.constant = 20 + width / 3 + spacing;
        self.collectionViewHeight.constant = 2 * width / 3;
        
        layout.itemSize = CGSizeMake(width / 3, width / 3);
        
    }else {
        
        self.collectionViewHeight.constant = 2 * width / 3 + spacing;
        layout.itemSize = CGSizeMake(width / 3, width / 3);
    }
    layout.minimumLineSpacing = spacing;
    layout.minimumInteritemSpacing = spacing;
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.scrollEnabled = NO;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    //注册cell
    [self.collectionView registerClass:[LLPhotoCell class] forCellWithReuseIdentifier:reuseIdentifier];
}




#pragma mark -- 他人主页
- (IBAction)headBtnAction:(id)sender {
    
    if ([_delegate respondsToSelector:@selector(homeCellDelegateWithButton:)]) {
        [_delegate homeCellDelegateWithButton:sender];
    }
}



- (void)setFrame:(CGRect)frame {

    frame.origin.y += 10;
    frame.size.height -= 10;
    [super setFrame:frame];
}


-(void)layoutSubviews
{
    [super layoutSubviews];
    
}



#pragma mark ---- UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.imgsArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LLPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    [cell.bigImgV sd_setImageWithURL:[NSURL URLWithString:self.imgsArray[indexPath.row]]];

    return cell;
}



- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    // 1 初始化
    LLPhotoBrowser *photoBrowser = [[LLPhotoBrowser alloc]init];
    // 2 设置代理
    photoBrowser.delegate = self;
    // 3 设置当前图片
    photoBrowser.currentImageIndex = indexPath.item;
    // 4 设置图片的个数
    photoBrowser.imageCount = self.imgsArray.count;
    // 5 设置图片的容器
    photoBrowser.sourceImagesContainerView = self.collectionView;
    // 6 展示
    [photoBrowser show];

}

//// 代理方法 返回图片URL
- (NSURL *)photoBrowser:(LLPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index{
    
    NSURL *url = [NSURL URLWithString:self.imgsArray[index]];
    
    return url;
}
// 代理方法返回缩略图
- (UIImage *)photoBrowser:(LLPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    
    LLPhotoCell *cell = (LLPhotoCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    
    return cell.bigImgV.image;
    
}



@end
